// 生成一个简单的线程例子
#include <thread>
#include <iostream>
#include <vector>
#include <memory>
void thread_function()
{
    std::cout << "Hello, World!" << std::endl;
}
// 增加一个thread 已经释放 但是任务还在执行的例子
void thread_function_2()
{
    // Simulate some work with a sleep
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Thread 2 finished execution!" << std::endl;
}
// 修改为线程容器
std::vector<std::unique_ptr<std::thread>> global_threads;

// ... existing code ...

void global_thread_function(int thread_id)
{
    for (int i = 0; i < 5; i++)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << "Global thread " << std::this_thread::get_id() << " running: " << i << std::endl;
    }
}
int main()
{
    std::thread t(thread_function);
    // 如果步join 则程序会崩溃 runtime error
    // t.join();
    t.join();
    // t.detach(); //有可能执行不玩

    std::thread t2(thread_function_2);
    t2.join();
    std::cout << "Thread t2 detached" << std::endl;

    // 分隔线
    std::cout << "--------------------------------" << std::endl;

    // 测试全局线程容器
    // 将线程对象放到容器中

    const int num_threads = 3;
    for (int i = 0; i < num_threads; i++)
    {
        global_threads.push_back(
            std::make_unique<std::thread>(global_thread_function, i));
        std::cout << "Created global thread " << i << std::endl;
    }

    // 等待所有全局线程完成
    for (auto &thread_ptr : global_threads)
    {
        if (thread_ptr && thread_ptr->joinable())
        {
            thread_ptr->join();
        }
    }

    // 清理容器
    global_threads.clear();
    std::cout << "Main thread finished" << std::endl;
    return 0;
}
